﻿#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
# Author:      doucube
#-------------------------------------------------------------------------------
#!/usr/bin/env python
#coding=utf-8

import os, io, sys, re, time
import winreg, json, random, subprocess
import webbrowser, urllib.request, urllib.parse
from lxml import etree
import lxml.html as HTML

#keyword = "abc"

#正则：用来过滤出页面正文搜索结果列表   
s_re_content = '<table cellpadding="0" cellspacing="0" class="result".+?</table>'  
#正则：用来过滤出页面正文搜索结果的标题   
s_re_content_title = '<font size="3">.+?</a>'  
#正则：用来过滤出页面正文搜索结果的摘要   
s_re_content_abstract = '<font size="?-1"?>.+?<br/?>'  
#正则：用来过滤出页面正文搜索结果的URL信息   
s_re_content_url = '<font color="#008000">.+?</font>' 

class BaiDu:
    def __init__( self ):
        self.__Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        self.__Ti = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2']

    def check( self, code ):
        if (len(code) != 17):
            print "必须为17位的字符"
            return False
        return True
        
    def calculate( self, code ):
        sum = 0
        for i in range(17):
            sum += int(code[i])*self.__Wi[i]
        return self.__Ti[sum%11]

def baidu(keyword):
    #construct the search command, example: ie=utf-8&wd=%E6%9D%A8%E5%B9%82&pn=0
    params = urllib.parse.urlencode({'wd': keyword.encode("utf-8"), 'pn': 0, "ie":"utf-8"})
    opener = urllib.request.build_opener()
    #add agent for simulate the browser, firefox
    opener.addheaders = [('User-agent', "Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1)")]
    response = opener.open("http://www.baidu.com/s?" + params)
    #get the response baidu result html
    bhtml = response.read().decode("utf-8")
    
    #use Xpath to verify the title is baidu search
    root = HTML.document_fromstring(bhtml)
    if root.xpath('''//title''')[0].text.find("百度搜索") != -1:
        print("获取页面成功！")
        return bhtml
    else:
        print("获取页面失败: " + "http://www.baidu.com/s?" + params)
        return "获取页面失败"


def main():
    keyword = "杨幂"
    pagehtml = baidu(keyword)
    
if __name__ == '__main__':
    main()
